#include "logmanager.h"
#include <fstream>
#include <sstream>
using namespace std;

static LogManager* instance = NULL;

LogManager::LogManager() : initialized(false)
{
	//ctor
}

LogManager::~LogManager()
{
	//dtor
}

void LogManager::Initialize(std::string basePath)
{
	LogManager& lm = GetInstance();
	if (lm.initialized == false)
	{
		lm.basePath = basePath;
		lm.initialized = true;
	}
	else
	{
		cerr << "Logmanager already initialized, multiple initializations not allowed";
	}
}

LogManager& LogManager::GetInstance()
{
	if (instance==NULL)
	{
		instance = new LogManager();
	}
	return *instance;
}

void LogManager::Log(string logName, string message)
{
	// Check of log object exists.
	LogManager& lm = GetInstance();

	if (lm.initialized)
	{
		sf::Lock(lm.ioMutex);

		ofstream* out = lm.GetOrCreateLog(logName);

		if (out != NULL )
		{
			clock_t ms = clock();
			*out << ms * 1000/ (CLOCKS_PER_SEC) << ": " << message << endl << flush;
		}
	}
	else
	{
		cerr << "Logmanager not initialized, initialize before using." << endl;
	}
}

ofstream* LogManager::GetOrCreateLog(string logName)
{
	// if this is first time we log, create fileobject.
	if (logFiles.find(logName) == logFiles.end())
	{
		ofstream* stream = new ofstream();
		stringstream x;
		x << basePath << "/" << logName << ".txt";
		stream->open(x.str().c_str(), ios::out | ios::app);
		logFiles[logName] = stream;
	}

	return logFiles[logName];
}
